// http://javascript.ruanyifeng.com/     JavaScript 标准参考教程——阮一峰
// https://www.cnblogs.com/woodyblog/p/6508524.html   参考链接
// https://www.cnblogs.com/jscode/archive/2013/04/27/3572239.html
// https://www.zhihu.com/question/24212111 		安卓机图片不能多选

var uploadApi = '/'
// 单次选择最多张数
var maxCount = 5
// 单次选择最大 M 数
var selectMaxSize = 1
var maxUploadSize = 2
var unit = 1024 * 1024
// 是否blob类型上传，blob可用压缩，
// file类型多图传送时，会丢失信息，少了一些图片
var isBlobUpload = true
// 是否加水印
var water = false

var eleFile = document.querySelector('#file')
var inputWrapper = $('#input-wrapper')
inputWrapper.files = []

var myFiles = []
var blobArr = []
var photoOrientation;

var fileAllData = []
if(isBlobUpload) {
	fileAllData = blobArr
} else {
	fileAllData = inputWrapper.files
}

// 缩放图片需要的canvas
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');

$('#input-wrapper').click(function(event) {
	eleFile.click()
});


eleFile.addEventListener('change', function (event) {


	if(this.files.length > maxCount) {
		alert('最多可选 '+ maxCount +' 张')
		return
	}
	var totalSize = 0
	for (var i = 0; i < this.files.length; i++) {
		totalSize += this.files[i].size
	}
	console.log('totalSize', totalSize, selectMaxSize * unit)
	// if(totalSize > selectMaxSize * unit) {
	// 	alert('单次选择不能超 '+ selectMaxSize +' M')
	// 	return
	// }

	console.log('files', this.files)
	myFiles = this.files


	for (var i = 0; i < myFiles.length; i++) {

		var imageType = /^image\//;
	    if (!imageType.test(myFiles[i].type)) {
	    	continue;
	    }

	    var canUpload = true
	    for (var j = 0; j < (inputWrapper.files).length; j++) {

	    	console.log('inputWrapper222', inputWrapper.files)

	    	if ((inputWrapper.files)[j].name == myFiles[i].name) {
	    		canUpload = false
	    		alert(myFiles[i].name + '重复上传')
	    		break
	    	}
	    }


	    if(canUpload) {
	    	inputWrapper.files.push(myFiles[i])

	    	if (inputWrapper.files) {
	    		 $('.submit-btn').css('display', 'block')
	    	} else {
	    		$('.submit-btn').css('display', 'none')
	    	}

			compressImg(myFiles[i])
	    }
	}

});


function compressImg(file) {

	// 获取图片的方向
	EXIF.getData(file, function () {
		photoOrientation = EXIF.getTag(file, 'Orientation')
	    console.log('photoOrientation', photoOrientation);
	    alert('phoOri：' + photoOrientation);
	});

	console.log('compress-begin')

	var reader = new FileReader();
	var img = new Image();

	var cFont = '18px microsoft yahei'
	var cStyle = "rgba(255,255,255,0.7)"
	var cText = "你是人间的四月猫"
	

	reader.readAsDataURL(file);
	reader.onload = function(e) {
		img.src =  e.target.result
	}


	// base64地址图片加载完毕后
	img.onload = function () {
	    // 图片原始尺寸
	    var originWidth = this.width;
	    var originHeight = this.height;
	    console.log(originWidth, originHeight)

	    // 最大尺寸限制
	    var maxWidth = 400, maxHeight = 400;
	    // 目标尺寸
	    var targetWidth = originWidth, targetHeight = originHeight;
	    // 图片尺寸超过400x400的限制
	    
	    if(originWidth > originHeight && originWidth > maxWidth) {
	    	targetWidth = maxWidth
	    	targetHeight = Math.round(maxWidth * (originHeight / originWidth));
	    } else if(originWidth < originHeight && originHeight > maxHeight) {
	    	targetHeight = maxHeight
	    	targetWidth = Math.round(maxHeight * (originWidth / originHeight));
	    }
	        
	    // canvas对图片进行缩放
	    canvas.width = targetWidth;
	    canvas.height = targetHeight;

	    console.log('999', targetWidth, targetHeight)

	    if(photoOrientation && photoOrientation != 1){
	        switch(photoOrientation){
	            case 6:
	                canvas.width = targetHeight;    
	                canvas.height = targetWidth;

	                // context.save(); 
	                context.rotate(Math.PI / 2);    
	                context.drawImage(this, 0, -targetHeight, targetWidth, targetHeight);
	                
                    // 加水印
                    if(water) {
                	    context.font = cFont;
                	    context.rotate(-Math.PI/2);
                	    context.fillStyle = cStyle;
                	    context.fillText(cText, 10, targetWidth - 10 );
                	    alert('water')
                    }
	                // context.restore();

	                break;
	            case 3:
	                context.rotate(Math.PI);    
	                context.drawImage(this, -targetWidth, -targetHeight, targetWidth, targetHeight);

                    // 加水印
                    if(water) {
                	    context.font = cFont;
                	    context.fillStyle = cStyle;
                	    context.fillText(cText, -targetWidth/2, -targetHeight/2);
                	    alert('water')
                    }

	                break;
	            case 8:
	                canvas.width = targetHeight;    
	                canvas.height = targetWidth;    
	                context.rotate(3 * Math.PI / 2);    
	                context.drawImage(this, -targetWidth, 0, targetWidth, targetHeight);

                    // 加水印
                    if(water) {
                	    context.font = cFont;
                	    context.fillStyle = cStyle;
                	    context.fillText(cText, -targetWidth/2, targetHeight/2);
                	    alert('water')
                    }

	                break;
	        }
	    }else{
	        context.drawImage(this, 0, 0, targetWidth, targetHeight);
            // 加水印
            if(water) {
        	    context.font = cFont;
        	    context.fillStyle = cStyle;
        	    context.fillText(cText, 10, targetHeight - 10);
            }
	    }

	    var myImgUrl = canvas.toDataURL("image/jpeg", 1);
	    console.log('myImgUrl', myImgUrl.length / unit)

	    var html = ''
	    html = '<div class="image-item">'
	    html += '<div class="remove-btn" data-name='+ file.name +'>x</div>'
	    html += '<img id="pic" src="'+ myImgUrl +'" />'
	    html += '</div>'
	    $('#input-wrapper').before(html)

	    
	    // canvas转为blob并上传
	    canvas.toBlob(function (blob) {

	    	var blobData = {
	    		name: file.name,
	    		data: blob
	    	}
	    	blobArr.push(blobData)

	    	if (blobArr.length) {
	    		 $('.submit-btn').css('display', 'block')
	    	} else {
	    		$('.submit-btn').css('display', 'none')
	    	}

	    }, file.type || 'image/png');

	};
}



function getObjectURL(file) {  
  	var url = null ;
  	if (window.createObjectURL!=undefined) { // basic
    	url = window.createObjectURL(file) ;  
  	} else if (window.URL!=undefined) { // mozilla(firefox)  
    	url = window.URL.createObjectURL(file) ;  
  	} else if (window.webkitURL!=undefined) { // webkit or chrome  
    	url = window.webkitURL.createObjectURL(file) ;  
  	}
  	return url;  
} 


// 点击上传
$('.submit-btn').click(function(event) {
	uploadHandler()
});

function uploadHandler() {

	var allFileSize = 0
	if(!isBlobUpload) {
		for (var i = 0; i < fileAllData.length; i++) {
			allFileSize += fileAllData[i].size
		}
		if(allFileSize > maxUploadSize * unit) {
			alert('每次上传最大尺寸为：'+ maxUploadSize + 'M')
			return
		}
	}

	var xhr = new XMLHttpRequest();
	var formData = new FormData();
	var allDone = false

	console.log('fileAllData', fileAllData)

	for(var i = 0, fitem; fitem = fileAllData[i]; i++){
		if((i+1) == fileAllData.length) {
			allDone = true
		}

		// console.log('upload-i', i)

		if(isBlobUpload) {
	    	formData.append('file', fitem.data, fitem.name);
		} else {
	    	formData.append('file', fitem);
		}
	}

	xhr.open('POST', uploadApi, true);
	xhr.onreadystatechange = function (e) {
	    if(xhr.readyState == 4){
	        if(xhr.status == 200){
	            console.log(xhr.responseText);
	            if(allDone) alert(xhr.responseText)
	        }else {
	            console.log(xhr.responseText);
	        }
	    }
	}

	xhr.send(formData);
}

// 删除图片
$('.image-wrapper').on('click', '.remove-btn', function(event) {
	event.preventDefault();
	var name = $(this).data('name')

	var fileIndex = null

	for (var i = 0; i < fileAllData.length; i++) {
		if(fileAllData[i].name == name) {
			fileIndex = i
		}
	}

	fileAllData.splice(fileIndex, 1)

	$(this).parent('.image-item').remove()
	if (fileAllData.length) {
		 $('.submit-btn').css('display', 'block')
	} else {
		$('.submit-btn').css('display', 'none')
	}

});
